


import QtQuick
import QtQuick.Window
import QtQuick.Controls
import QtQuick.Layouts
import QtQuick.Dialogs
import SceneRendererAdapter
import "./"


ApplicationWindow {
    id: root_window
    width: 640
    height: 480
    visible: true
    title: "solar_1"
/*
=========================================================================
头部菜单栏：File、Edit、Run----------每个button都有一个下拉菜单
！！！待补充：下拉菜单没有写，每个菜单的点击事件没有写
！！！待完善：这里menu可以写成一个qml组件
*/
    menuBar: MenuBar{
        id:menuBar

        //contentHeight: 20
        Menu {
            title: "File"
            Action{ text:"Open"}
            Action{ text:"New"}
            MenuSeparator { }
            Action{ text:"close"}

            implicitWidth: 100


            delegate:MenuItem{
                id:menuItem_1
                implicitWidth: 100
                implicitHeight: 20

                contentItem:Text{
                    text:menuItem_1.text
                    font:menuItem_1.font
                    color:menuItem_1.highlighted? "white":"green"
                    horizontalAlignment: Text.AlignLeft
                    verticalAlignment: Text.AlignHCenter
                    elide:Text.ElideRight
                }

                background:Rectangle{
                    color:menuItem_1.highlighted ? "green": "white"

                }

            }
            //！！！这里，menuItem的边框被盖住了,先设置为透明
            background:Rectangle{
                border.width:1
                border.color:"transparent"
            }

        }
        Menu {
            title: "Edit"
            Action{ text:"Open"}
            Action{ text:"New"}
            MenuSeparator { }
            Action{ text:"close"}

            implicitWidth: 100


            delegate:MenuItem{
                id:menuItem_2
                implicitWidth: 100
                implicitHeight: 20

                contentItem:Text{
                    text:menuItem_2.text
                    font:menuItem_2.font
                    color:menuItem_2.highlighted? "white":"green"
                    horizontalAlignment: Text.AlignLeft
                    verticalAlignment: Text.AlignHCenter
                    elide:Text.ElideRight
                }

                background:Rectangle{
                    color:menuItem_2.highlighted ? "green": "white"

                }

            }
            //！！！这里，menuItem的边框被盖住了,先设置为透明
            background:Rectangle{
                border.width:1
                border.color:"transparent"
            }

        }
        Menu {
            title: "Run"
            Action{ text:"Open"}
            Action{ text:"New"}
            MenuSeparator { }
            Action{ text:"close"}

            implicitWidth: 100


            delegate:MenuItem{
                id:menuItem_3
                implicitWidth: 100
                implicitHeight: 20

                contentItem:Text{
                    text:menuItem_3.text
                    font:menuItem_3.font
                    color:menuItem_3.highlighted? "white":"green"
                    horizontalAlignment: Text.AlignLeft
                    verticalAlignment: Text.AlignHCenter
                    elide:Text.ElideRight
                }

                background:Rectangle{
                    color:menuItem_3.highlighted ? "green": "white"

                }

            }
            //！！！这里，menuItem的边框被盖住了,先设置为透明
            background:Rectangle{
                border.width:1
                border.color:"transparent"
            }


        }

        delegate:MenuBarItem{
            id:menuBarItem
            height:23
            anchors.top: parent.top
            contentItem:Text{
                text:menuBarItem.text
                font:menuBarItem.font
                opacity:enabled?1.0:0.3
                color:menuBarItem.highlighted? "white":"green"
                horizontalAlignment: Text.AlignLeft
                verticalAlignment: Text.AlignHCenter
                elide:Text.ElideRight
            }

            background: Rectangle{
                //implicitHeight: 20
                implicitWidth: 40
                opacity:enabled?1:0.3
                color:menuBarItem.highlighted ? "green":"white"
            }

        }

        background: Rectangle{
            implicitHeight: 20
            implicitWidth: 40
            color:"white"
            Rectangle{              //绿色分割线
                color:"green"
                width:parent.width
                height:1
                anchors.bottom: parent.bottom
            }
        }

        Component.onCompleted: {
            console.log('contentheight:',contentHeight)
        }

    }


/*
==========================================================================
头部工具栏：几个icon图标------------每个icon图标也可以做对应的下拉菜单（如果需要的话）
！！！待补充：点击事件没有写
！！！待完善：ToolButton可以写成一个qml组件或者component、repeater
*/
    header:ToolBar{
        id: toolbar
        height:23

        Row{
            anchors.fill:parent

            //把图标换掉！！！
            //弹出新的窗口后，在新窗口关闭之前，不可以对原窗口进行操作！！！

            // run ray tracing 
            //或许可以加一个ToolTip,当鼠标浮在上面出现tip
            //添加点击事件---弹出一个窗口



            //----button - to run ray tracing simulation------
            ToolButton{
                
                height:parent.height
                width:30
                icon.source: "qrc:/image/menu_icon/start.png"
                icon.color:"#36ab60"
                icon.height:22
                hoverEnabled:true
                background:Rectangle{
                    color: parent.hovered ? (parent.pressed ? "lightgreen":"lightgray") 
                                : "white"
                }

                RayTracingWindow{
                    id: ray_tracing_window
                }
                onClicked:{
                    ray_tracing_window.show();
                }
            }

            // -----button - to run analysis function---------
            ToolButton{
                height:parent.height
                width:30
                icon.source:"qrc:/image/menu_icon/system.png"
                icon.color:"#36ab60"
                icon.height:22
                hoverEnabled:true
                background:Rectangle{
                    color: parent.hovered ? (parent.pressed ? "lightgreen":"lightgray") 
                                : "white"
                }

                AnalyticFunctionWindow{
                    id: analytic_function_window
                }
                onClicked:{
                    analytic_function_window.show() ;
                }
            }

            // -----button - to show diagram of Flux Map-----
            ToolButton{
                height:parent.height
                width:30
                icon.source: "qrc:/image/menu_icon/parameter.png"
                icon.color:"#36ab60"
                icon.height:22
                hoverEnabled:true
                background:Rectangle{
                    color: parent.hovered ? (parent.pressed ? "lightgreen":"lightgray") 
                                : "white"
                }

                DataVisualizationWindow{
                    id: data_visualization_window
                }
                onClicked:{
                    data_visualization_window.show()
                }
            }
           
        }

        Rectangle{      //分割线
            height:1
            width: root_window.width
            anchors.bottom: parent.bottom// Pane{
//     anchors.fill: parent
//     focus: Qt.ClickFocus
// }
            anchors.right: root_window.right
            anchors.left: root_window.left
            color:"#36ab60"
        }

        background:Rectangle{
            color:"white"
        }

    }

    

/*
==========================================================================
页脚：Text展示一些信息
*/
    footer:ToolBar{
        height:20

        Rectangle{      //分界线
            height:1
            width:parent.width
            anchors.top: parent.top
            color:"gray"
        }

        Text{
            text:"This is a footer"
            font.pointSize: 8
            color:"gray"
            anchors.left: parent.left
        }
        background: Rectangle{
            color:"lightgray"
        }
    }




/*
==========================================================================
正文内容：SplitView把界面分为左右两部分，左边：3D可视化窗口，右边:树状视图和参数设置
*/
    SplitView{
        anchors.fill: parent
        orientation: Qt.Horizontal
        // background: Rectangle
        // {
        //     color: "black"
        // }
        /*
        -------------------------------------------------------------------
        正文左边：3D可视化窗口
        ！！！待补充：需要与OpenGL或Qt3D结合
        */
        Item {
            id:leftItem
            implicitWidth: parent.width * 0.6
            SplitView.maximumWidth: parent.width        //注意：同一个rectangle里，不要同时设置maximum和minimum
            onWidthChanged: 
            {
                scene_renderer_adapter.setParentSizeWidth(leftItem.width)
            }
            onHeightChanged: 
            {
                scene_renderer_adapter.setParentSizeHeight(leftItem.height)
            }
            // color: "black"
            // Label {
            //     text: "View 1"
            //     anchors.centerIn: parent
            // }
            
                MouseArea
                {
                    id: scene_renderer_outside_mousearea
                    property real last_mouse_x : 0.0
                    property real last_mouse_y : 0.0
                    property bool key_alt_pressed : false
                    anchors.fill: parent
                    hoverEnabled: true
                    z: 100
                    onPressed: 
                    {
                        // console.log("mouse onPressed1")
                    }
                    onEntered: {
                        scene_renderer_adapter.focus = true
                    }
                    onPositionChanged: (mouse) =>
                    {
                        // console.log("mouse onPositionChanged1")
                        // console.log(mouse.x)
                        // console.log(mouse.y)
                        var delta_mouse_x = mouse.x - last_mouse_x
                        var delta_mouse_y = mouse.y - last_mouse_y
                        last_mouse_x = mouse.x
                        last_mouse_y = mouse.y
                        if (!(delta_mouse_x > 50.0 || delta_mouse_x < -50.0 || delta_mouse_y > 50.0 || delta_mouse_y < -50.0) && key_alt_pressed)
                        {
                            scene_renderer_adapter.rotateLookAtCenter(delta_mouse_x / 10.0, delta_mouse_y / 10.0)
                        }
                        mouse.accepted = true;
                    }
                    SceneRendererAdapter
                    {
                        id: scene_renderer_adapter
                        objectName: "scene_renderer_adapter"
                        // z: 99
                        property bool change_look_at_center : false
                        Keys.enabled: true  // 不设置按键使能，获取不了按键事件
                        // focus: true         // 不设置焦点，获取不了键盘事件
                        Keys.onPressed: (event) =>
                        {
                            // if (event.key === Qt.Key_Q)
                            // {
                            //     console.log("Q Pressed")
                            //     scene_renderer_adapter.updateHeliostats()
                            //     event.accepted = true;
                            // }
                            if (event.key === Qt.Key_Left)
                            {
                                console.log("← Pressed")
                                algorithmProcessor.testQmlContext()
                                scene_renderer_adapter.rotateLookAtCenterHorizontal(-5)
                                event.accepted = true;
                            }
                            if (event.key === Qt.Key_Right)
                            {
                                console.log("→ Pressed")
                                scene_renderer_adapter.rotateLookAtCenterHorizontal(5)
                                event.accepted = true;
                            }
                            if (event.key === Qt.Key_Up)
                            {
                                console.log("↑ Pressed")
                                scene_renderer_adapter.rotateLookAtCenterVertical(-5)
                                event.accepted = true;
                            }
                            if (event.key === Qt.Key_Down)
                            {
                                console.log("↓ Pressed")
                                scene_renderer_adapter.rotateLookAtCenterVertical(5)
                                event.accepted = true;
                            }
                            if (event.key === Qt.Key_Alt)
                            {
                                console.log("Alt Pressed")
                                scene_renderer_outside_mousearea.key_alt_pressed = !scene_renderer_outside_mousearea.key_alt_pressed
                                event.accepted = true;
                            }
                            if (event.key === Qt.Key_8)
                            {
                                console.log("8 Pressed")
                                if (change_look_at_center)
                                {
                                    scene_renderer_adapter.moveLookAtCenter(0, 5, 0)
                                }
                                else
                                {
                                    scene_renderer_adapter.moveCameraCenter(0, 5, 0)
                                }
                                event.accepted = true;
                            }
                            if (event.key === Qt.Key_2)
                            {
                                console.log("2 Pressed")
                                if (change_look_at_center)
                                {
                                    scene_renderer_adapter.moveLookAtCenter(0, -5, 0)
                                }
                                else
                                {
                                    scene_renderer_adapter.moveCameraCenter(0, -5, 0)
                                }
                                event.accepted = true;
                            }
                            if (event.key === Qt.Key_4)
                            {
                                console.log("4 Pressed")
                                if (change_look_at_center)
                                {
                                    scene_renderer_adapter.moveLookAtCenter(5, 0, 0)
                                }
                                else
                                {
                                    scene_renderer_adapter.moveCameraCenter(5, 0, 0)
                                }
                                event.accepted = true;
                            }
                            if (event.key === Qt.Key_6)
                            {
                                console.log("6 Pressed")
                                if (change_look_at_center)
                                {
                                    scene_renderer_adapter.moveLookAtCenter(-5, 0, 0)
                                }
                                else
                                {
                                    scene_renderer_adapter.moveCameraCenter(-5, 0, 0)
                                }
                                event.accepted = true;
                            }
                            if (event.key === Qt.Key_1)
                            {
                                console.log("1 Pressed")
                                if (change_look_at_center)
                                {
                                    scene_renderer_adapter.moveLookAtCenter(0, 0, 5)
                                }
                                else
                                {
                                    scene_renderer_adapter.moveCameraCenter(0, 0, 5)
                                }
                                event.accepted = true;
                            }
                            if (event.key === Qt.Key_0)
                            {
                                console.log("0 Pressed")
                                if (change_look_at_center)
                                {
                                    scene_renderer_adapter.moveLookAtCenter(0, 0, -5)
                                }
                                else
                                {
                                    scene_renderer_adapter.moveCameraCenter(0, 0, -5)
                                }
                                event.accepted = true;
                            }
                            if (event.key === Qt.Key_Control)
                            {
                                console.log("ctrl Pressed")
                                change_look_at_center = !change_look_at_center
                                event.accepted = true;
                            }
                            if (event.key === Qt.Key_Plus)
                            {
                                console.log("+ Pressed")
                                scene_renderer_adapter.increaseTime()
                                event.accepted = true;
                            }
                            event.accepted = true;
                        }
                        MouseArea
                        {
                            z: 98
                            anchors.fill: parent
                            hoverEnabled: true
                            propagateComposedEvents: true
                            onEntered: {
                                scene_renderer_adapter.focus = true
                            }
                            onPressed: (mouse) =>
                            {
                                // console.log("mouse onPressed2")
                                mouse.accepted = false;
                            }
                            onPositionChanged: (mouse) =>
                            {
                                // console.log("mouse onPositionChanged2")
                                // console.log(mouse.button)
                                mouse.accepted = false;
                            }
                        }
                    }
                }
            
            
        }

        /*
        -------------------------------------------------------------------
        正文右边：树状视图+参数设置
        */
        Rectangle{
            id:rightItem
            SplitView.minimumWidth: 10
            SplitView.fillWidth: true;
            //color:"lightgray"


            SplitView{
                anchors.fill: parent
                orientation: Qt.Vertical

                /*
                  ---------------------------------------------
                  上部：树状视图部分，建立模型，包括顶部的一行菜单和stackview
                */
                Rectangle{
                    implicitHeight: parent.height/2
                    SplitView.maximumHeight: parent.height
                    //color: "red"


                    //---------------------------------------------
                    // 文件输入部分
                    Rectangle{
                        id: file_set_row
                        height: 20
                        anchors.top:parent.top
                        anchors.left: parent.left
                        anchors.right: parent.right

                        //button，点击后弹出文件选择界面
                        Button{
                            id: file_set_btn
                            anchors.left: parent.left
                            anchors.leftMargin: 10
                            anchors.verticalCenter: parent.verticalCenter
            
                            width: 15
                            height: 15

                            onClicked:{
                                file_set_fds.open()
                            }
                        }

                        //显示文件名，也可以写成TextField，用来输入文件
                        Rectangle{
                            id: file_set_rect
                            border.width:1
                            border.color: "gray"
                            anchors.left: file_set_btn.right
                            anchors.leftMargin: 10
                            anchors.verticalCenter: parent.verticalCenter
                            anchors.right: file_run_algorithm.left
                            anchors.rightMargin: 10
                            height: 18

                            Label{
                                id: file_set_label
                                anchors.fill: parent
                                anchors.margins: 3
                
                                text: "input file: .json"
                                font.pointSize: 8
                                verticalAlignment: Text.AlignVCenter

                                onTextChanged:{
                                    console.log("file set to " + file_set_label.text)
                                    algorithmProcessor.setJsonFilePath(file_set_label.text)
                                    /**
                                    * TODO::对world和tree node的节点参数进行更改
                                    *       即对paratreemodel和topotreemodel进行更改（需要在其中增加处理文件的方法）
                                    */
                                }

                            }
                        }
                        Button{
                            id: file_run_algorithm
                            anchors.right: file_make_ui_scene.left
                            anchors.rightMargin: 10

                            
                            anchors.verticalCenter: parent.verticalCenter
                            
                            width: 15
                            height: 15

                            // color: "blue"
                            
                            text: "Run"
                            background:Rectangle{
                                color: "blue"
                            }

                            onClicked:{
                                console.log("run algorithm via file settings")
                                algorithmProcessor.runFile()
                            }
                            
                        }

                        // button, 点击后把文件应用到ui上，即在ui界面设置文件中的参数
                        Button{
                            id: file_make_ui_scene
                            anchors.right: parent.right
                            anchors.rightMargin: 10
                            
                            anchors.verticalCenter: parent.verticalCenter
                            
                            // color: "red"
                            text:"ui"
                            background:Rectangle{
                                color: "red"
                            }
                            
                            width:15
                            height:15

                            onClicked:{
                                /**
                                    对ui场景进行更改,包括tree model，simulation para
                                */
                                console.log("alter ui settings via file")
                                topoControl.setTopoTreeViaFile(file_set_label.text)
                                rayTracingParameter.setParameterViaFile(file_set_label.text)
                            }

                        }

                        //弹窗：选择输入文件
                        FileDialog{
                            id: file_set_fds
                            title: "选择文件"
                            //currentFolder: shortcuts.desktop    //！！！这里报错shortcuts没有定义
                            //selectExisting: true
                            //selectFolder: false
                            //selectMultiple: false
                            nameFilters: ["json文件 (*.json)"]
                            onAccepted:{
                            // console.log("You chose: " + world_file_set_fds.fileUrl)

                                file_set_label.text = selectedFile
                            }

                         }
                    }

                    //----------------------------------------------
                    //顶部的一行菜单：两个按钮：world、scene
                    Row{
                        id: menuRow
                        height:20
                        anchors.top: file_set_row.bottom
                        anchors.left:parent.left
                        anchors.right:parent.right
                        //color:"pink"

                        Component{

                            id: rightUpperMenuBtn_delegate

                            Button{
                                id:rightUpperMenu_btn
                                height:parent.height
                                width:60
                                Text{
                                    text:modelData
                                    anchors.centerIn: parent
                                    font.family: "微软雅黑"
                                    font.pointSize: 8
                                    color:rightUpperMenu_btn.pressed ? "black":"gray"
                                }
                                background: Rectangle{
                                    color:rightUpperMenu_btn.hovered?"lightgray":"white"
                                }
                                onClicked: {
                                    upper_st.currentIndex = index
                                }

                            }

                        }
                        Repeater{
                            model:['world','topology']
                            delegate: rightUpperMenuBtn_delegate
                        }

                    }


                    //----------------------------------------------
                    //菜单与stackLayout的分割线
                    Rectangle{
                        id: spliter
                        anchors.top: menuRow.bottom
                        anchors.left: parent.left
                        anchors.right: parent.right
                        height: 1
                        color: "black"
                    }


                    //---------------------------------------------
                    //StackLayout
                    StackLayout{
                        id: upper_st
                        anchors.top:spliter.bottom
                        anchors.bottom:parent.bottom
                        anchors.left:parent.left
                        anchors.right:parent.right

                        currentIndex: 0



                        MyRect_World{
                            
                        }

                        MyRect_Topology{

                        }

                    }

                }


                /*
                 ---------------------------------------------
                 下部：参数设置部分，是一个stackview，stackview内的每个界面都是一个treeview
                */
                Rectangle{
                    SplitView.minimumHeight: 20
                    SplitView.fillHeight: true
                    color: "skyblue"



                    StackLayout
                    {
                        id: lower_st
                        anchors.fill: parent

                        currentIndex: 0

                        // Component{
                            
                        // }

                        Repeater{
                            
                            id: para_st_repeater
                            //model: paraControl.getParaTreeModelCnt()
                            model: paraControl.para_cnt
                            

                            delegate: Rectangle{
                                color: "pink"
                                Text{               //先写个Text判断页面有没有换
                                    id: temporary_text
                                    anchors.top: parent.top
                                    anchors.left: parent.left
                                    anchors.right: parent.right
                                    height: 20

                                    text: paraControl.getLabelTxt(index)
                                }

                                //！！！！这个组件还有很多需要更改
                                // 问题：：每次Index对应的index都会更改，是每次都会变化吗
                                ParaTreeView{
                                    anchors.top: temporary_text.bottom
                                    anchors.left: parent.left
                                    anchors.right: parent.right
                                    anchors.bottom: parent.bottom 

                                    treeModel: paraControl.getTreeModel(index)
                                    paraTreeId: index
                                }
                            }

                            // 每次topo中增加节点或删除节点，就会重新加载所有的para model
                            // ！！！重新加载后，会导致之前设置的参数变回初始值----是否是数据结构没有改变
                            function repeaterModelCntChange(){
                                para_st_repeater.model = paraControl.para_cnt
                            }

                            Component.onCompleted:{
                                paraControl.paraTreeCntChanged.connect(repeaterModelCntChange)
                            }
                        }

                        //假设Topo总共有x个节点，world总共有6个，则总共需要x+6个ParaTreeView
//                        Repeater{
//                            id: repeater
//                            //model: topoControl.getTotalNodeCnt() + 6    //这里也可以是对paraControl进行处理
//                            model: 2    //先写2个

//                            ParaTreeView
//                            {
//                                treeModel: paraControl.getTreeModel(repeater.index)
//                            }
//                        }


                    }

                }
            }

        }


    }

}
